<?php
namespace App\Http\Controllers\Api;
use App\Enums\RetStatusEnum;
use App\Enums\ShelfStatusEnum;
use App\Http\Controllers\Controller;
use App\Models\Good;
use App\Models\GoodsCategory;
use App\Models\HotWords;
use App\Models\Navigation;
use App\Models\OperatePosition;
use App\Models\Rage;
use App\Models\Recommend;
use App\Models\WheelPicture;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;


class IndexController extends Controller
{
    public function advertising(){
        try {
            if (!($fid = Cache::get('fid'))){
                $fid = DB::table('open_screen')
                    ->select(['title','hit_type','hit_content','thumb','second'])
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('weight','desc')
                    ->first();
                Cache::put('fid', $fid, 60);
            }
            $data=[
                'domain'=>getenv('APP_URL').'storage/',
                'advertising'=>$fid
            ];
            appMessage(0,'ok',$data);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function index(){//APP首页数据
        try {
            if (!($data = Cache::get('index_page_data'))) {
                $goodsCategoryModel = GoodsCategory::query();
                $goodsCategory = $goodsCategoryModel
                    ->where('status','=',1)
                    ->where('level','=',1)
                    ->orderBy('sort','desc')
                    ->get(['id','cate_name','img'])
                    ->toArray();
                $wheelPictureModel = WheelPicture::query();
                $banner = $wheelPictureModel
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('weight','desc')
                    ->limit(10)
                    ->get(['title','hit_type','hit_content','thumb'])
                    ->toArray();
                $navigationModel = Navigation::query();
                $navigation = $navigationModel
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('weight','desc')
                    ->limit(5)
                    ->get(['title','hit_type','hit_content','thumb'])
                    ->toArray();
                $operatePositionModel = OperatePosition::query();
                $operatePosition = $operatePositionModel
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('weight','desc')
                    ->limit(3)
                    ->get(['internal_name','title','abstract','hit_type','hit_content','thumb'])
                    ->toArray();
                $rageModel =  Rage::query()
                    ->leftJoin('goods', function ($join) {
                        $join->on('goods.id', '=', 'rage.hit_content');
                    });
                $rage = $rageModel
                    ->where('rage.start_time','<=',date('Y-m-d H:i:s'))
                    ->where('rage.end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('rage.weight','desc')
                    ->limit(5)
                    ->get(['goods.id','goods.goods_name','goods.pic_url','goods.sell_price','goods.actual_price','goods.tao_sale','goods.coupon_amount'])
                    ->toArray();
                $goodsModel = Good::query();
                $goods = $goodsModel
                    ->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF)
                    ->orderBy('weigh','desc')
                    ->orderBy('sort','desc')
                    ->limit(10)
                    ->get(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount'])
                    ->toArray();
                $domain=getenv('APP_URL').'storage/';
                $data=compact('domain','goodsCategory','banner','navigation','operatePosition','rage','goods');
                Cache::put('index_page_data', $data, 60);
            }
            appMessage(0,'ok',$data);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function getMore(){//APP首页加载更多商品
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        try {
            $goodsModel = Good::query();
            $goods=$goodsModel
                ->select(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount'])
                ->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF)
                ->orderBy('weigh','desc')
                ->orderBy('sort','desc')
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$goods['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function getActivityGoods(){
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'id'   => 'required | in:1,2,3,4',
            'sort' => 'in:asc,desc',
            'orderBy' => 'in:1,2,3',
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $id=$param["id"];
        $sort=  $param["sort"] ?? '';
        $orderBy= $param["orderBy"] ?? '';
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        $orderByColumn=null;
        switch ($orderBy){
            case 1://按券的大小
                $orderByColumn='coupon_amount';
                break;
            case 2://按淘宝销量
                $orderByColumn='tao_sale';
                break;
            case 3://按到手价
                $orderByColumn='actual_price';
                break;
        }
        try {
            $goodsModel =Good::query()
            ->select(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount']);
            switch ($id){
                case 1://9快9包邮
                    $goodsModel=$goodsModel
                        ->where('actual_price','<',10);
                    break;
                case 2://网红爆款
                    $goodsModel=$goodsModel
                        ->where('goods_name','like','%抖音%')
                        ->where('goods_name','like','%网红%')
                        ->where('goods_name','like','%小红书%')
                        ->where('goods_name','like','%ins%');
                    break;
                case 3://白菜价
                    $goodsModel=$goodsModel
                        ->where('actual_price','<',30);
                    break;
                case 4://每日神券
                    $goodsModel=$goodsModel
                        ->where('coupon_amount','>=',30)
                        ->where('coupon_remain_count','>',0)
                        ->where('retStatus','=',RetStatusEnum::NORMAL);
                    break;
            }
            $goodsModel=$goodsModel
                ->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF);
            if(!empty($orderByColumn) && !empty($sort))
                $goodsModel=$goodsModel ->orderBy($orderByColumn,$sort);
            $goods=$goodsModel
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$goods['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function getMoreRageGoods(){
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        try {
            $rageModel =  Rage::query()
                ->leftJoin('goods', function ($join) {
                    $join->on('goods.id', '=', 'rage.hit_content');
                });
            $rage = $rageModel
                ->select(['goods.id','goods.goods_name','goods.pic_url','goods.sell_price','goods.actual_price','goods.tao_sale','goods.coupon_amount'])
                ->where('rage.start_time','<=',date('Y-m-d H:i:s'))
                ->where('rage.end_time','>',date('Y-m-d H:i:s'))
                ->where('goods.shelf_status','=',ShelfStatusEnum::UPPERSHELF)
                ->orderBy('rage.weight','desc')
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$rage['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }

    public function getGoodsByCateId(){//获取二级分类商品
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'cateId'   => 'required | integer',
            'sort' => 'in:asc,desc',
            'orderBy' => 'in:1,2,3',
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $cateId=$param["cateId"];
        $sort=  $param["sort"] ?? '';
        $orderBy= $param["orderBy"] ?? '';
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        $orderByColumn=null;
        switch ($orderBy){
            case 1://按券的大小
                $orderByColumn='coupon_amount';
                break;
            case 2://按淘宝销量
                $orderByColumn='tao_sale';
                break;
            case 3://按到手价
                $orderByColumn='actual_price';
                break;
        }
        try {
            $goodsModel =Good::query()
                ->select(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount']);
            $goodsModel=$goodsModel
                ->where('cate_id','=',$cateId);
            $goodsModel=$goodsModel ->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF);
            if(!empty($orderByColumn) && !empty($sort))
                $goodsModel=$goodsModel->orderBy($orderByColumn,$sort);
            $goods=$goodsModel
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$goods['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function getGoodsByCatePid(){//获取一级分类商品
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'catePid'   => 'required | integer',
            'sort' => 'in:asc,desc',
            'orderBy' => 'in:1,2,3',
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $catePid=$param["catePid"];
        $sort=  $param["sort"] ?? '';
        $orderBy= $param["orderBy"] ?? '';
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        $orderByColumn=null;
        switch ($orderBy){
            case 1://按券的大小
                $orderByColumn='coupon_amount';
                break;
            case 2://按淘宝销量
                $orderByColumn='tao_sale';
                break;
            case 3://按到手价
                $orderByColumn='actual_price';
                break;
        }
        try {
            $goodsModel =Good::query()
                ->select(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount']);
            $goodsModel=$goodsModel
                ->where('cate_pid','=',$catePid);

            $goodsModel=$goodsModel->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF);
            if(!empty($orderByColumn) && !empty($sort))
                $goodsModel=$goodsModel->orderBy($orderByColumn,$sort);
            $goods=$goodsModel
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$goods['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function getSearchWords(){
        try {
            $param = request()->all();
            $validator = \Validator::make($param, [
                'token'   => 'string'//nullable
            ]);
            $error = $validator->errors()->first();
            if ($error)
                appMessage(1,$error);
            $userId=null;
            if(!empty($param['token'])){
                $userInfo =getMemberIdByToken($param['token']);
                $userId=empty($userInfo) ? null : $userInfo->id;
            }
            if (!($recommend = Cache::get('recommend'))){
                $recommend=Recommend::query()
                    ->select('search_word')
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->orderBy('weight','desc')
                    ->first()->toArray();
                Cache::put('recommend', $recommend, 60);
            }
            $search_history=[];
            if(!empty($userId)){
                $res=DB::table("search")->where(['member_id'=>$userId])->first(['key_words']);
                if (!empty($res))
                    $search_history=explode(',',$res->key_words);
            }
            if (!($hot_words = Cache::get('hot_words'))){
                $hot_words =HotWords::query()
                    ->select(['search_word','font_color'])
                    ->where('start_time','<=',date('Y-m-d H:i:s'))
                    ->where('end_time','>',date('Y-m-d H:i:s'))
                    ->limit(12)
                    ->orderBy('weight','desc')
                    ->get()
                    ->toArray();
                Cache::put('hot_words', $hot_words, 60);
            }
            appMessage(0,'ok',compact('recommend','search_history','hot_words'));
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }
    public function searchGoods(){
        $param = request()->all();
        $validator = \Validator::make($param, [     //正则验证
            'goods_name'   => 'required | string',
            'token'   => 'string',
            'sort' => 'in:asc,desc',
            'orderBy' => 'in:1,2,3',
            'page' => 'integer',
            'pageSize' => 'integer'
        ]);
        $error = $validator->errors()->first();
        if ($error)
            appMessage(1,$error);
        $goods_name=$param["goods_name"];
        $sort=  $param["sort"] ?? '';
        $orderBy= $param["orderBy"] ?? '';
        $pageSize = empty($param["pageSize"]) ? 20 : $param["pageSize"];
        $orderByColumn=null;
        switch ($orderBy){
            case 1://按券的大小
                $orderByColumn='coupon_amount';
                break;
            case 2://按淘宝销量
                $orderByColumn='tao_sale';
                break;
            case 3://按到手价
                $orderByColumn='actual_price';
                break;
        }
        try {
            $userId=null;
            if(!empty($param['token'])){
                $userInfo =getMemberIdByToken($param['token']);
                $userId=empty($userInfo) ? null : $userInfo->id;
            }
            if(!empty($userId)){
                $res=DB::table("search")->where(['member_id'=>$userId])->first(['id','key_words']);
                if(empty($res)){
                    DB::table('search')->insert([
                        'member_id'=>$userId,
                        'key_words' => $goods_name,
                    ]);
                }else{
                    $key_words_arr=explode(',',$res->key_words);
                    array_unshift($key_words_arr,$goods_name);
                    $key_words_arr=array_unique($key_words_arr);
                    if(count($key_words_arr)>12)
                        $key_words_arr=array_slice($key_words_arr,0,12);
                    DB::table("search")
                        ->where('id', $res->id)
                        ->update(['key_words'=>implode(',',$key_words_arr)]);
                }
            }
            $goodsModel = Good::query()
                ->select(['id','goods_name','pic_url','sell_price','actual_price','tao_sale','coupon_amount']);
            $goodsModel=$goodsModel
                ->where('goods_name','like','%'.$goods_name.'%')
                ->where('shelf_status','=',ShelfStatusEnum::UPPERSHELF);
            if(!empty($orderByColumn) && !empty($sort))
                $goodsModel=$goodsModel->orderBy($orderByColumn,$sort);
            $goods=$goodsModel
                ->paginate($pageSize)
                ->toArray();
            appMessage(0,'ok',$goods['data']);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }

    public function getRecommendWords()
    {
        try {
            $param = request()->all();
            $validator = \Validator::make($param, [
                'search_word'   => 'required | string'
            ]);
            $error = $validator->errors()->first();
            if ($error)
                appMessage(1,$error);
            $recommend=Recommend::query()
                ->select('recommend_word')
                ->where('search_word','like',$param['search_word'].'%')
                ->where('start_time','<=',date('Y-m-d H:i:s'))
                ->where('end_time','>',date('Y-m-d H:i:s'))
                ->limit(12)
                ->orderBy('weight','desc')
                ->get()
                ->toArray();

            appMessage(0,'ok',$recommend);
        } catch (\Exception $e) {
            appMessage(1,$e->getMessage());
        }
    }

}